package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            String line = readLine();
            System.out.println(line);
            Map<String,String> headers = new HashMap<>();
            while (true){
                line = readLine();
                if (line.isEmpty()){
                    break;
                }
                String[] data = line.split(":\\s");
                headers.put(data[0],data[1]);
            }
            headers.forEach((k,v) -> System.out.println(k+":"+v));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char cur , pre = 'a';
        while ((d = in.read()) != -1){
            cur = (char) d;
            if (cur == 10 && pre ==13){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }
}
